package com.pet.platform.controller;

import com.pet.platform.common.Result;
import com.pet.platform.dto.CartItemDTO;
import com.pet.platform.service.CartService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/cart")
@RequiredArgsConstructor
public class CartController {
    private final CartService cartService;
    
    // 默认使用ID为1的用户
    private static final Long DEFAULT_USER_ID = 1L;

    @GetMapping
    public Result<List<CartItemDTO>> getCartItems() {
        // 尝试获取当前用户ID，如果未登录则使用默认ID
        Long userId = getUserId();
        return Result.success(cartService.getCartItems(userId));
    }

    @PostMapping
    public Result<Void> addToCart(@RequestParam Long productId, @RequestParam Integer quantity) {
        Long userId = getUserId();
        cartService.addToCart(userId, productId, quantity);
        return Result.success();
    }

    @PutMapping("/{id}/quantity")
    public Result<Void> updateQuantity(@PathVariable Long id, @RequestParam Integer quantity) {
        Long userId = getUserId();
        cartService.updateQuantity(userId, id, quantity);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Void> removeFromCart(@PathVariable Long id) {
        Long userId = getUserId();
        cartService.removeFromCart(userId, id);
        return Result.success();
    }

    @DeleteMapping
    public Result<Void> clearCart() {
        Long userId = getUserId();
        cartService.clearCart(userId);
        return Result.success();
    }
    
    /**
     * 获取当前用户ID，如果未登录则返回默认ID
     */
    private Long getUserId() {
        return DEFAULT_USER_ID;
    }
}